"""
A cross-platform pager utility
>>> import pager
>>> pager.write(text)
"""
import sys
import os
import re
import tempfile
import types


def _getpager():
    """decide what method to use for paging through text."""
    if type(sys.stdout) is not types.FileType:
        return _plainpager
    
    if not sys.stdin.isatty() or not sys.stdout.isatty():
        return _plainpager
    
    if os.getenv('TERM') in ['dumb', 'emacs']:
        return _plainpager
    
    if 'PAGER' in os.environ:
        if sys.platform == 'win32': # pipes completely broken in Windows
            return lambda text: _tempfilepager(_plainify(text), os.environ['PAGER'])
        elif os.environ.get('TERM') in ['dumb', 'emacs']:
            return lambda text: _pipepager(_plainify(text), os.environ['PAGER'])
        else:
            return lambda text: _pipepager(text, os.environ['PAGER'])
    
    if sys.platform == 'win32' or sys.platform.startswith('os2'):
        return lambda text: _tempfilepager(_plainify(text), 'more <')
    
    if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
        return lambda text: _pipepager(text, 'less')
    
    import tempfile
    (fd, filename) = tempfile.mkstemp()
    os.close(fd)
    try:
        if hasattr(os, 'system') and os.system('more %s' % filename) == 0:
            return lambda text: pipepager(text, 'more')
        else:
            return ttypager
    finally:
        os.unlink(filename)

def _plainify(text):
    """remove formatting from text"""
    return re.sub('.\b', '', text)

def _pipepager(text, cmd):
    """page through text by feeding it to another program."""
    pipe = os.popen(cmd, 'w')
    try:
        pipe.write(text)
        pipe.close()
    except IOError:
        # Ignore broken pipes caused by quitting the pager program.
        pass

def _tempfilepager(text, cmd):
    """page through text by invoking a program on a temporary file."""
    fd, filename= tempfile.mkstemp()
    file = os.fdopen(fd, "w")
    file.write(text)
    file.close()
    try:
        os.system(cmd + ' ' + filename)
    finally:
        os.unlink(filename)

def _ttypager(text):
    """page through text on a text terminal (mimicking 'more')"""
    try:
        import tty
        fd = sys.stdin.fileno()
        old = tty.tcgetattr(fd)
        tty.setcbreak(fd)
        getchar = lambda: sys.stdin.read(1)
    except (ImportError, AttributeError):
        tty = None
        try:
            from msvcrt import getch as getchar
        except ImportError:
            getchar = lambda: sys.stdin.readline()[:-1][:1]
    
    lines = _plainify(text).splitlines()
    pagesize = os.getenv("LINES", 25) - 1
    rowindex = 0
    cmd = "n"
    
    try:
        while lines[rowindex:]:
            sys.stdout.write("\r          \r")
            if cmd in "qQ":
                break
            elif cmd in "\r\n":
                rowindex += 1
                sys.stdout.write(lines[rowindex])
                sys.stdout.write("\n")
            elif cmd in "bB\x1b":
                ri = rowindex - pagesize
                if ri < 0:
                    pass
                if ri < pagesize:
                    rowindex = ri
                else:
                    rowindex = ri
                    sys.stdout.write("\n".join(lines[rowindex:rowindex+pagesize]))
                    sys.stdout.write("\n")
            else:
                sys.stdout.write("\n".join(lines[rowindex:rowindex+pagesize]))
                sys.stdout.write("\n")
                rowindex += pagesize
            
            if not lines[rowindex:]:
                break
            sys.stdout.write("-- more --")
            sys.stdout.flush()
            cmd = getchar()
    except KeyboardInterrupt:
        pass
    finally:
        sys.stdout.write("\r          \r")
        if tty:
            tty.tcsetattr(fd, tty.TCSAFLUSH, old)

def _plainpager(text):
    """simply print unformatted text (the ultimate fallback)"""
    sys.stdout.write(_plainify(text))

_pager = _getpager()

#
# API
#
def write(text):
    _pager(text)




if __name__ == "__main__":
    _ttypager("""<HTML>

<HEAD>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<TITLE>OSNews.com</TITLE>
<meta name="description" content="OSNews.com informs you about the latest news on a vast range of operating systems, from the well-known mainstream OSes, down to small embedded (but also very interesting technically) ones.">
<meta name="keywords" content="OSNews, OS News, Operating System, Linux, BeOS, Unix, Windows, Microsoft, AtheOS, Irix, AIX, Solaris, MacOS, MacOSX, Apple, OS2, QNX, Amiga, NewOS, Inferno, Plan9, NeXT, SkyOS, BSD, FreeBSD, OpenBSD, Mandrake, Caldera, Red Hat, SuSE, NetBSD, TrustedBSD, Mach">
<link REL="top" TITLE="OSNews.com - Exploring the Future of Computing" HREF="//osnews.com/" >
<link REL="search" TITLE="Search OSNews" HREF="//osnews.com/search.php?search=">
<link REL="alternate" TITLE="OSNews RSS" HREF="//osnews.com/files/recent.xml" TYPE="application/rss+xml">
<link REL="shortcut icon" HREF="/favicon.ico" TYPE="image/x-icon">
<meta http-equiv="Pragma" content="no-cache">
<meta HTTP-EQUIV="ROBOTS" content="INDEX, FOLLOW">


<STYLE type="text/css">
<!--
A.non:link{COLOR: #5E741C; TEXT-DECORATION: none;}
A.non:visited{COLOR: #5E741C; TEXT-DECORATION: none;}
A.non:hover{COLOR: #FF6600; TEXT-DECORATION: underline;}

A:link{COLOR: #5E741C; TEXT-DECORATION: underline;}
A:visited{COLOR: #5E741C; TEXT-DECORATION: underline;}
A:hover{COLOR: #FF6600; TEXT-DECORATION: underline;}

body {
scrollbar-arrow-color: #000000;
scrollbar-base-color: #003300;
scrollbar-dark-shadow-color: #999900;
scrollbar-track-color: #808080;
scrollbar-face-color: #DEDEDE;
scrollbar-shadow-color: #DDDDDD;
scrollbar-highlight-color: #CCCCCC;
scrollbar-3d-light-color: #003300;
}

.table { 
border : 2px; 
border-color : #FFFFFF; 
border-style : groove;
border-collapse: collapse;
border-spacing: 0px;
} 

.td {
border : 2px; 
border-color : #eeeeee; 
border-style : groove;
border-spacing: 0px;
}

.td2 {
border : 2px; 
border-color : #eeeeee; 
border-style : groove;
border-spacing: 0px;
}

.td3 {
border : 1px; 
border-color : #bbbbbb; 
border-style : solid;
border-spacing: 0px;
}-->

</STYLE>
<script LANGUAGE="JavaScript1.2"> 
<!--
function addNetscapePanel() { 
      if ((typeof window.sidebar == "object") && (typeof window.sidebar.addPanel == "function")) 
     { 
         window.sidebar.addPanel ("OSNews.com", "http://www.osnews.com/mozilla.php",""); 
      } 
      else 
      { 
         var rv = window.confirm ("This feature is only available for the Mozilla browser. " + "Would you like to download Mozilla now?"); 
         if (rv) 
            document.location.href = "http://www.mozilla.org";
      } 
   } 
//-->
</SCRIPT>

<!-- BEGIN: AdSolution-Tag 4.3: Global-Code [PLACE IN HTML-HEAD-AREA!] -->
<script type="text/javascript" language="javascript" src="http://a.as-us.falkag.net/dat/dlv/aslmain.js"></script>
<!-- END: AdSolution-Tag 4.3: Global-Code -->

</HEAD>
<body bgcolor="#D2D9D2" link="#5E741C" vlink="#5E741C" topmargin=0 marginheight=0 marginwidth=0 leftmargin=0 rightmargin=0>
<center>

<table cellpadding=0 cellspacing=0 border=0><tr><td valign="Middle" align="center"><!-- begin OSNews general -->
<!-- Netshelter Interstitial Code -->
<!-- BEGIN: AdSolution-Website-Tag 4.3 : OS News / Interstitial -->""")

















